package com._54programer.ws;

import java.util.HashSet;
import java.util.Set;

import org.springframework.stereotype.Component;

import com._54programer.config.HazelcastRunner;
import com._54programer.entity.CGroup;
import com._54programer.entity.CUser;
import com._54programer.ws.handler.WsServerHandler;
import com.alibaba.fastjson.JSON;
import com.hazelcast.core.IMap;

import io.netty.channel.ChannelHandlerContext;
import io.netty.util.AttributeKey;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@Component
public class CBind {

	// *********common**********//
	public void bindCGroup(ChannelHandlerContext ctx, String groupId) throws Exception {
		
		// { "groupid1": [] ,"groupid2": [] ,........ },组对象
		// { "uid1": ["gp1","gp2",.....] ,"uid2": ["gp1","gp3",.....] ,........ },组对象
		// { "uid1" : {} ,"uid2" :{},.......} 用户对象uid
		// { "username1" : {} ,"username2" :{},.......} 用户对象username
		IMap<Object, Object> ActiveCGroup = HazelcastRunner.ExpHi.getMap("ActiveCGroup");
		

		User uu = (User) ctx.channel().attr(AttributeKey.valueOf("USER")).get();
		if (uu == null) {
			uu.setUId(null);
			uu.setUsername(null);
		}
		
		CGroup cgMain = new CGroup();
		cgMain.setGpid(WsServerHandler.GROUP_ID);
		CUser cuMain = new CUser();
		cuMain.setUchannel(ctx.channel());
		cuMain.setUchannelid(ctx.channel().id());
		cuMain.setUid(uu.getUId());
		cuMain.setUusername(uu.getUsername());
		Set<CUser> gpuserMain = new HashSet<>();
		gpuserMain.add(cuMain);
		cgMain.setGpuser(gpuserMain);
		HazelcastRunner.ExpHi.getSet("ActiveCGroup").add(JSON.toJSON(cgMain));
		log.warn(">>>>>>>初始化组模块成功:{}",HazelcastRunner.ExpHi.getSet("ActiveCGroup").toArray());
		

//		CGroup cg = null;
//		if (ActiveCGroup.size() > 0 && !ActiveCGroup.contains(groupId)) {
//			System.err.println("11111111111111111");
//			cg = new CGroup();
//			cg.setGpid(groupId);
//			Set<CUser> gpuser = new HashSet<>();
//			CUser cu = new CUser();
//			cu.setUchannel(ctx.channel());
//			cu.setUchannelid(ctx.channel().id());
//			cu.setUid(uu.getUId());
//			cu.setUusername(uu.getUsername());
//			gpuser.add(cu);
//			System.err.println(cg.toString());
//			cg.setGpuser(gpuser);
//			HazelcastRunner.ExpHi.getList("ActiveCGroup").add(JSON.toJSON(cg));
//		} else {
//			int index = 0;
//			for (Object cGroup : ActiveCGroup) {
//				CGroup cG = JSON.toJavaObject(JSONObject.parseObject(cGroup.toString()), CGroup.class);
//				if (groupId.equals(cG.getGpid()) && Objects.equals(groupId, cG.getGpid())) {
//					CUser cu = new CUser();
//					cu.setUchannel(ctx.channel());
//					cu.setUchannelid(ctx.channel().id());
//					cu.setUid(uu.getUId());
//					cu.setUusername(uu.getUsername());
//					cG.getGpuser().add(cu);
//					HazelcastRunner.ExpHi.getList("ActiveCGroup").set(index, JSON.toJSON(cG));
//				}
//				index++;
//			}
//		}
//		log.info("CGroup:{}", HazelcastRunner.ExpHi.getList("ActiveCGroup").toArray());
	}
}
